package com.ckzp.jfinal.system.util;

import com.ckzp.core.util.JwtUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.core.Results;
import com.ckzp.jfinal.system.WebSite;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by 51594 on 2020/2/26.
 */
public class ValidateRole {

    public String jwt = "";

    public static ValidateRole n(String jwt) {
        return new ValidateRole(jwt);
    }


    public static ValidateRole n(HttpServletRequest request) {
        String jwt = WebSite.getJwt(request);
        return new ValidateRole(jwt);
    }

    public ValidateRole(String jwt) {
        this.jwt = jwt;
    }

    public boolean v(String pass_roles) {
        boolean has_roles = false;
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);

            String user_roles = js.getRoles() + "|login|";
            if (user_roles != null) {
                if (user_roles.indexOf("|administrator|") > -1) {//超级用户全通过
                    has_roles = true;
                } else {
                    String[] user_roless = StringUtil.split(user_roles, "|");
                    for (int k = 0; k < user_roless.length; k++) {
                        String role = user_roless[k];
                        if (role != null && role.length() > 0 && pass_roles.indexOf("|" + role + "|") > -1) {
                            has_roles = true;
                            break;
                        }
                    }
                }
            }
        } else {
            has_roles = false;
        }
        return has_roles;
    }
}
